package com.webank.wedatasphere.qualitis.controller.thymeleaf;

import com.alibaba.fastjson.JSONObject;
import com.webank.wedatasphere.qualitis.project.entity.DataSourcePoJo;
import com.webank.wedatasphere.qualitis.response.Grid;
import com.webank.wedatasphere.qualitis.response.Resp;
import com.webank.wedatasphere.qualitis.rule.dao.repository.RuleModelRepository;
import com.webank.wedatasphere.qualitis.rule.dao.repository.TemplateRepository;
import com.webank.wedatasphere.qualitis.rule.entity.RuleModelInfo;
import com.webank.wedatasphere.qualitis.rule.entity.Template;
import com.webank.wedatasphere.qualitis.util.CommUtils;
import com.webank.wedatasphere.qualitis.util.LocalTimeUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 规则模板台账
 */
@RestController
@RequestMapping("/ruleModel")
public class RuleModelController {


    @Autowired
    private RuleModelRepository repository;


    /**
     * 数据源
     *
     * @return
     */
    @RequestMapping(value = {"/list"}, method = RequestMethod.GET)
    public ModelAndView question() {
        return new ModelAndView("layui-admin/rulemodel/list");
    }


    /**
     * 问题工单
     *
     * @return
     */
    @RequestMapping(value = {"/detail"}, method = RequestMethod.GET)
    public ModelAndView detail(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("layui-admin/rulemodel/detail");
        String id = request.getParameter("id");
        if (StringUtils.isNotBlank(id)) {
            repository.findById(Long.valueOf(id)).ifPresent(view::addObject);
        } else {
            view.addObject(new RuleModelInfo());
        }
        return view;
    }

    @RequestMapping(value = {"/updateOrSave"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Resp<DataSourcePoJo> updateOrSave(RuleModelInfo ruleModelInfo) {
        if (ruleModelInfo.getId() == null) {
            ruleModelInfo.setCreateTime(LocalTimeUtils.getCurrentTime());
            ruleModelInfo.setUpdateTime(LocalTimeUtils.getCurrentTime());
            ruleModelInfo.setCreateUser("admin");
        } else {
            ruleModelInfo.setUpdateTime(LocalTimeUtils.getCurrentTime());
        }
        repository.saveAndFlush(ruleModelInfo);
        return Resp.Ok();
    }

    @RequestMapping(value = {"/remove"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @Transactional
    public Resp<DataSourcePoJo> remove(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (StringUtils.isNotBlank(ids)) {
            String[] split = ids.split(",");
            for (String id : split) {
                repository.deleteById(Long.valueOf(id));
            }
        }
        return Resp.Ok();
    }

    @RequestMapping(value = {"/datagrid"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Grid<?> getCountIndex(HttpServletRequest request) {
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        //  分页查询
        String page = request.getParameter("page");
        String limit = request.getParameter("rows");
        // 获取条件过滤器
        JSONObject changeBuilder = CommUtils.getJsonObject(request);
        // 组装SQl条件过滤法器
        ExampleMatcher matcher = CommUtils.getSqlWhere(request);
        // 序列化对象
        RuleModelInfo itemQueryWhere = changeBuilder.toJavaObject(RuleModelInfo.class);
        // 分页插件
        Pageable pageable = PageRequest.of(Integer.parseInt(page) - 1, Integer.parseInt(limit), sort);
        // 条件过滤器插件
        Example<RuleModelInfo> example = Example.of(itemQueryWhere, matcher);
        // 条件过滤+分页
        Page<RuleModelInfo> all = repository.findAll(example, pageable);
        List<RuleModelInfo> content = all.getContent();
        System.out.println(content);
        long totalElements = all.getTotalElements();
        return Grid.OkPage(CollectionUtils.isEmpty(content)?new ArrayList<>():content, totalElements);
    }

}